from flask import session, jsonify, request, redirect, url_for, make_response
from werkzeug.security import check_password_hash, generate_password_hash

from models import db
from models.index import User
from . import passport_blu


@passport_blu.route("/login", methods=["GET", "POST"])
def login():
    telephone = request.json.get('telephone')
    password = request.json.get('password')
    user = db.session.query(User).filter(User.phone == telephone).first()
    if user and check_password_hash(user.pwd_hash, password):
        ret = {
            "err": 0,
            "errmsg": "登录成功"
        }
        session['user_id'] = user.id
        session['nick_name'] = user.nick_name
        session['avatar_url'] = user.avatar_url

    else:
        ret = {
            "err": 35,
            "errmsg": "手机号或密码错误"
        }
    return jsonify(ret)


@passport_blu.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index_blu.index'))


@passport_blu.route("/image_code")
def image_code():
    # 真正的生成一张图片数据
    from utils.captcha.captcha import captcha
    # 生成验证码
    name, text, image = captcha.generate_captcha()
    print("刚刚生成的验证码：", text)
    # 通过session的方式，缓存刚刚生成的验证码，否则注册时不知道刚刚生成的是多少
    session['auth_code'] = text
    # 返回响应内容
    resp = make_response(image)
    # 设置内容类型
    resp.headers['Content-Type'] = 'image/png'
    return resp


@passport_blu.route("/register", methods=["GET", "POST"])
def register():
    # 1. 提取数据
    telephone = request.json.get("telephone")
    password = request.json.get("password")
    auth_code = request.json.get("auth_code")
    # 验证图片验证码是否正确
    if session.get("auth_code").upper() != auth_code.upper():
        ret = {
            "err": 996,
            "errmsg": "验证码有误，请重输"
        }
        return jsonify(ret)

    # 查询相同的用户
    if db.session.query(User).filter(User.phone == telephone).first():
        return jsonify({
            "err": 93,
            "errmsg": "该手机号已被注册"
        })

    # 注册用户
    user = User()
    user.nick_name = telephone
    user.phone = telephone
    user.pwd_hash = generate_password_hash(password)
    user.avatar_url = "../../static/img/user.png"
    try:
        db.session.add(user)
        db.session.commit()
        # 注册成功之后，立刻认为登录成功，也就说需要进行状态保持
        session['user_id'] = user.id
        session['telephone'] = telephone
        session['avatar_url'] = user.avatar_url
        ret = {
            "err": 0,
            "errmsg": "注册成功..."
        }
    except Exception:
        ret = {
            "err": 1002,
            "errmsg": "注册失败..."
        }
    return jsonify(ret)
